let taskData = null;
let timer = null;
let canPush = true;
const phonePush = () => {
  if (canPush) {
    canPush = false;
    setTimeout(() => {
      canPush = true;
    }, 60 * 1000 * 5);
    // let mobiles = ["17719870822", "13703862144"];
    let mobiles = ["17719870822"];
    const param = {
      mobiles,
      source: "tb采券",
    };
    fetch("http://msapi.maishou88.com/api/v1/service/sendSmsForAbnormal", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(param),
    }).then((response) => {
      if (!response.ok) {
        throw new Error("Network response was not ok");
      }
      return response.json();
    });
  }
};
const getTask = () => {
  fetch("https://msadmin.maishou88.com/api/v1/couponTask/getTask")
    .then((response) => response.text())
    .then((data) => {
      const res = JSON.parse(data);
      if (res.code && res.code === 200 && res.data && res.data.taskUrl) {
        taskData = res.data;
        const u = res.data.taskUrl;
        let url = u.split("?")[0];
        url = url.split("//")[1];
        taskData["url"] = url;
        chrome.tabs.create({
          url: taskData.taskUrl,
        });
      } else {
        if (timer) {
          clearTimeout(timer);
          timer = null;
        }
        timer = setTimeout(getTask, 5000);
      }
    })
    .catch(() => {
      if (timer) {
        clearTimeout(timer);
        timer = null;
      }
      timer = setTimeout(getTask, 5000);
    });
};
chrome.runtime.onInstalled.addListener(() => {
  getTask();
  chrome.runtime.onMessage.addListener(function (
    message,
    sender,
    sendResponse
  ) {
    if (message.action === "doTask") {
      if (taskData && taskData.taskId) {
        const param = {
          couponInfo: message.data,
          taskId: taskData.taskId,
        };
        taskData.taskId = null;
        fetch("https://msadmin.maishou88.com/api/v1/couponTask/submitTask", {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify(param),
        })
          .then((response) => {
            if (!response.ok) {
              throw new Error("Network response was not ok");
            }
            return response.json();
          })
          .finally(() => {
            const uu = taskData.url.split("?");
            if (timer) {
              clearTimeout(timer);
              timer = null;
            }
            timer = setTimeout(getTask, 2000);
            chrome.tabs.query({}, function (tabs) {
              if (taskData.url) {
                const target = tabs.filter((item) => {
                  return item.url.includes(uu[0]);
                });
                if (target.length > 0) {
                  let num = 0;
                  target.forEach((element) => {
                    chrome.tabs.remove(element.id, function () {
                      num++;
                      if (num === target.length) {
                        taskData = null;
                        if (timer) {
                          clearTimeout(timer);
                          timer = null;
                        }
                        timer = setTimeout(getTask, 2000);
                      }
                    });
                  });
                }
              }
            });
          });
      }
    }
    if (message.data === "FAIL_SYS_SESSION_EXPIRED::SESSION失效") {
      phonePush();
    }
  });
});
